package com.ryskoo.config.shiro;

import com.ryskoo.customer.vendor.domain.VendorPO;
import com.ryskoo.customer.vendor.service.IVendorService;
import com.ryskoo.customer.vendormanager.domain.VendorManagerPO;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


public class ManagerRealm extends AuthorizingRealm {

	@Autowired
	private IVendorService vendorService;
    /**
     * 授权用户权限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
       // ManagerDTO mdto = (ManagerDTO) principals.getPrimaryPrincipal();
//        ReturnMessageDTO<List<RoleDTO>> returnDto = roleConsumer.getRolesByManagerName(mdto.getLoginName());
//        if (returnDto != null && ReturnCodeEnum.SUCCESS.getReturnCode() == returnDto.getReturnCode()) {
//            List<RoleDTO> roleList = returnDto.getReturnMessage();
//            if (roleList != null && roleList.size() > 0) {
//                for (RoleDTO role : roleList) {
//                    authorizationInfo.addRole(role.getName());
//                    for (PermissionDTO permission : role.getPermissionList()) {
//                        authorizationInfo.addStringPermission(permission.getExpress());
//                    }
//                }
//            }
//        }
        return authorizationInfo;
    }

    /**
     * 验证用户身份
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) authcToken;

		// 获取用户的输入的账号.
		String usernameAndVendorname = (String) upToken.getPrincipal();
		String[] user = usernameAndVendorname.split(",");
		String userName = "";
		String vendorName = "";
		if(user !=null && user.length > 0){
			userName = user[0];
			vendorName = user[1];
		}

		// 通过登录名+商户名称从数据库中查找 User对象，如果找到，没找到.
		// 实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
		VendorManagerPO manager = null; 
		VendorPO vendor = vendorService.getVendorByLoginNameAndVendorName(userName, vendorName);
		if (null != vendor) {
			manager = vendor.getVendorManger();
		}
        if (manager == null) {
            // 账户不对
            throw new UnknownAccountException();
        }
        // 盐值
        ByteSource credentialsSalt = ByteSource.Util.bytes(manager.getLoginName());
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
        		manager, // 用户名
        		manager.getPassword(), // 密码
                credentialsSalt, getName());
        return authenticationInfo;
    }
}
